package com.sxm.yiwei.activitis;

import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.view.ContextThemeWrapper;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.adapters.HotSendLinkItemAdapter;
import com.sxm.yiwei.tools.BaseIntents;
import com.sxm.yiwei.tools.CropPictures;
import com.sxm.yiwei.tools.Data;
import com.sxm.yiwei.tools.IsLogin;
import com.sxm.yiwei.tools.SendBookTime;
import com.sxm.yiwei.utils.InternetAddressUtis;
import com.sxm.yiwei.utils.SPopupWindow;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class HotSendActivity extends BaseActivity implements View.OnClickListener{

    private ImageView sengback;

    private Button one;
    private Button two;
    private Button three;
    private Button four;

    private List<String> imglist = new ArrayList();
    private static final int PHOTO_TEXT = 3022;
    private static final int PHOTO_PICKED_WITH_DATA = 3021;
    /*用来标识请求照相功能的activity*/
    private static final int CAMERA_WITH_DATA = 3023;


    private SPopupWindow takePhotoPopWin;
    private WindowManager.LayoutParams params;
    private ImageView hotimg1;
    private ImageView hotimg2;
    private ImageView hotimg3;
    private ImageView hotimg4;
    private Bitmap photo;
    private String path1;
    private int currentIndex;
    private ImageView selecttype;
    private LinearLayout imgs;
    private EditText inExplain;
    private SharedPreferences sharedPreferences;
    private String appId;
    private String userId;
    private String token;
    private Button updata;
    private LinearLayout chooselink;

    private TextView linktext;
    private List<HashMap<String, String>> backLink;
    private List<Double> distance;
    private EditText inputsafe;
    private Double allDistance = 0.0;
    private double v;
    private List<HashMap<String, String>> contData;
    private HashMap<String, String> cont;
    private double vd;
    private int weightnum;
    private int weightmoney;
    private String explain;
    private String time;
    private String safe;
    private double vsafe;
    private DecimalFormat df = new DecimalFormat("######0.00");
    private ListView gotlistview;
    private Double dSafe;
    private TextView hotx;
    private CheckBox hotbox;
    private RelativeLayout timepick;
    private TextView picktimetext;
    private LinearLayout imgline;
    private RelativeLayout hotlink;
    private ImageView selectIntro;
    private long l;
    private ImageView backmain;
    private List<HashMap<String, String>> listdata;

    public HotSendActivity() {}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hot_send);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid","1");
        userId = sharedPreferences.getString("userId", "0");
        token = sharedPreferences.getString("token", "2");
        initSendView();
        hotbox.setChecked(true);
        contData = new ArrayList<>();
        l = System.currentTimeMillis();
       SendBookTime sendBookTime = new SendBookTime();
        String result = sendBookTime.getTime(l);
        String[] split = result.split("/");
        picktimetext.setText(split[1]);
        time = split[0];
        weightnum = 0;
        weightmoney=0;
        one.setSelected(true);
    }


    //初始化控件
    private void initSendView() {
        selectIntro = (ImageView) findViewById(R.id.hotsend_selectintro);
        timepick = (RelativeLayout) findViewById(R.id.hotsend_timepick);
        picktimetext = (TextView) findViewById(R.id.hotsend_picktime);
        hotlink = (RelativeLayout) findViewById(R.id.hotsend_link);
        hotbox = (CheckBox) findViewById(R.id.hotsend_box);
        hotx = (TextView) findViewById(R.id.hot_x);
        sengback = (ImageView) findViewById(R.id.seng_back);
        selecttype = (ImageView) findViewById(R.id.send_selecttype);
        imgs = (LinearLayout) findViewById(R.id.hotsend_imgs);
        backmain = (ImageView) findViewById(R.id.hotsend_backmain);
        one = (Button) findViewById(R.id.hotsend_weight1);
        two = (Button) findViewById(R.id.hotsend_weight2);
        three = (Button) findViewById(R.id.hotsend_weight3);
        four = (Button) findViewById(R.id.hotsend_weight4);
        hotimg1 = (ImageView) findViewById(R.id.hot_img1);
        hotimg2 = (ImageView) findViewById(R.id.hot_img2);
        hotimg3 = (ImageView) findViewById(R.id.hot_img3);
        inputsafe = (EditText) findViewById(R.id.hotsend_inputsafe);
        gotlistview = (ListView) findViewById(R.id.hot_listview);
        imgline = (LinearLayout) findViewById(R.id.hotsend_imgline);
        inExplain = (EditText) findViewById(R.id.hotsend_explain);
        updata = (Button) findViewById(R.id.hotsend_updata);
        chooselink = (LinearLayout) findViewById(R.id.hotsend_chooeslink);
        linktext = (TextView) findViewById(R.id.hotsend_linktext);

        // 设置点击事件
        timepick.setOnClickListener(this);
        selectIntro.setOnClickListener(this);
        /*---------------------------*/
        backmain.setOnClickListener(this);

        sengback.setOnClickListener(this);
        selecttype.setOnClickListener(this);

        hotimg1.setOnClickListener(this);
        hotimg2.setOnClickListener(this);
        hotimg3.setOnClickListener(this);

        updata.setOnClickListener(this);
        chooselink.setOnClickListener(this);

        hotx.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.hotsend_backmain:
                startActivity(new Intent(HotSendActivity.this, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
            case R.id.hotsend_selectintro:
                Intent intenttype = new Intent(HotSendActivity.this,HotSendSelectTypeActivity.class);
                intenttype.putExtra("from","1");
                startActivityForResult(intenttype,100);
                break;
            case R.id.hot_x:
                Intent i = new Intent(HotSendActivity.this,WEBXActivity.class);
                i.putExtra("from","hot");
                i.putExtra("url", InternetAddressUtis.XNOSEND);
                startActivity(i);
                break;
            case R.id.seng_back:
                finish();
                break;
            case R.id.hotsend_timepick:
                takePhotoPopWin = new SPopupWindow(this,this);
//        设置Popupwindow显示位置（从底部弹出）
                takePhotoPopWin.showAtLocation(findViewById(R.id.main_view), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
                params = getWindow().getAttributes();
                //当弹出Popupwindow时，背景变半透明
                params.alpha=0.7f;
                getWindow().setAttributes(params);
                //设置Popupwindow关闭监听，当Popupwindow关闭，背景恢复1f
                takePhotoPopWin.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        params = getWindow().getAttributes();
                        params.alpha=1f;
                        getWindow().setAttributes(params);
                    }
                });
                takePhotoPopWin.setOnCilckButton(new SPopupWindow.OnClickButton() {
                    @Override
                    public void OnClickButton(String s,String stime) {

                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date date = null;
                        try {
                            date = simpleDateFormat.parse(stime);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        long ts = date.getTime();
                        if (ts>l){
                            picktimetext.setText(s);
                            time=stime;
                        }else {

                        }
                    }
                });
                break;
            case R.id.hotsend_weight1:
                one.setSelected(true);
                two.setSelected(false);
                three.setSelected(false);
                four.setSelected(false);
                weightnum=0;
                weightmoney=0;
                break;
            case R.id.hotsend_weight2:
                one.setSelected(false);
                two.setSelected(true);
                three.setSelected(false);
                four.setSelected(false);
                weightnum=1;
                weightmoney=10;
                break;
            case R.id.hotsend_weight3:
                one.setSelected(false);
                two.setSelected(false);
                three.setSelected(true);
                four.setSelected(false);
                weightnum=2;
                weightmoney=20;
                break;
            case R.id.hotsend_weight4:
                one.setSelected(false);
                two.setSelected(false);
                three.setSelected(false);
                four.setSelected(true);
                weightnum=3;
                weightmoney=30;
                break;
            case R.id.send_selecttype:
                imgs.setVisibility(View.VISIBLE);
                imgline.setVisibility(View.VISIBLE);
                break;
            case R.id.hot_img1:
                currentIndex=0;
                doPickPhotoAction();
                break;
            case R.id.hot_img2:
                currentIndex=1;
                doPickPhotoAction();
                break;
            case R.id.hot_img3:
                currentIndex=2;
                doPickPhotoAction();
                break;
            case R.id.hotsend_chooeslink:
                if (IsLogin.isLogin()){
                    Intent intentcall = new Intent(HotSendActivity.this,MineAdresser.class);
                    intentcall.putExtra("from","2");
                    startActivityForResult(intentcall,2);
                }else {

                }
                break;

            case R.id.hotsend_updata:
                if (IsLogin.isLogin()){
                    if (!hotbox.isChecked()){
                        Toast.makeText(this, "请阅读同意相关协议", Toast.LENGTH_SHORT).show();
                    }else {
                        explain = String.valueOf(inExplain.getText());
                        if (!explain.equals("")){
                            if (contData.size()!=0){
                                reckonCost();
                                Double sd = Double.valueOf(safe);
                                if (sd>=20.0){
                                    explain = String.valueOf(inExplain.getText());
                                    Intent intent = new Intent(HotSendActivity.this,HotSendBookActivity.class);
                                    Bundle b = new Bundle();
                                    b.putSerializable("cont", (Serializable) contData);
                                    b.putSerializable("link", (Serializable) backLink);
                                    b.putSerializable("imglist", (Serializable) imglist);
                                    Log.d("tag", "onClick: 添加参数--"+allDistance);
                                    b.putString("alldistance", allDistance+"");
                                    b.putString("explain", explain);
                                    b.putString("weight", String.valueOf(weightnum));
                                    b.putString("v", String.valueOf(df.format(vd)));
                                    b.putString("safe", safe);
                                    b.putString("time", time);
                                    intent.putExtras(b);
                                    startActivity(intent);
                                    finish();
                                }else {
                                    Toast.makeText(this, "保价不得低于20元", Toast.LENGTH_SHORT).show();
                                }
                            }else {
                                Toast.makeText(this, "请填写联系人", Toast.LENGTH_SHORT).show();
                            }
                        }else {
                            Toast.makeText(this, "请填写您的订单简介信息", Toast.LENGTH_SHORT).show();
                        }
                    }
                }else {}
                break;
        }
    }

    // 计算订单费用

    private void reckonCost(){
        //df = new DecimalFormat("######0.00");
        double di = 0.0;
        double lastdouble = 0.0;
        for (int i = 0; i < contData.size(); i++) {
            String dis1 = contData.get(i).get("distance");
            String format = df.format(Double.valueOf(dis1));
            Double dist = Double.valueOf(format);
            allDistance+=dist;

            Log.d("tag", "reckonCost: nihao --"+dis1+"//"+dist);

        }



        safe = String.valueOf(inputsafe.getText());
        if (safe.equals("")){
            safe="0";
        }else {
        }
        dSafe = Double.valueOf(safe);
        // 保价
        vsafe = dSafe * 0.05;

        if (contData==null){}else {
            if (contData.size()==1){
                for (int i = 0; i < contData.size(); i++) {
                    String dis1 = contData.get(i).get("distance");
                    String format = df.format(Double.valueOf(dis1));
                    Double dist = Double.valueOf(format);
                    if (dist>3){
                        vd = (dist-3)*2+9+vsafe+weightmoney;
                    }else {
                        vd = 9 + vsafe+weightmoney;
                    }

                }
            }else {
                for (int i = 1; i < contData.size(); i++) {
                    String dis1 = contData.get(i).get("distance");
                    String format = df.format(Double.valueOf(dis1));
                    Double dist = Double.valueOf(format);
                    lastdouble +=dist;
                }
                String dis1 = contData.get(0).get("distance");
                String format = df.format(Double.valueOf(dis1));
                Double dist = Double.valueOf(format);
                if (dist>3){
                    vd = (dist-3)*2+9+vsafe+weightmoney;
                }else {
                    vd = 9 + vsafe+weightmoney;
                }
                double v = (allDistance-dist) * 2 + (contData.size()- 1) * 5;

                vd = v+vd;
            }
        }

    }

    BaseIntents baseIntents = new BaseIntents();
    // 调用相机/相册
    private void doPickPhotoAction() {
        final Context context = this;
        AlertDialog.Builder b1 = new AlertDialog.Builder(context);
        View view = LayoutInflater.from(context).inflate(R.layout.picture_dialog, null);
        b1.setView(view);

        TextView camere = (TextView) view.findViewById(R.id.picdia_camere);
        TextView pic = (TextView) view.findViewById(R.id.picdia_pic);
        TextView cancel1 = (TextView) view.findViewById(R.id.picdia_cancel);

        final AlertDialog dialog1 = b1.create();
        Window window = dialog1.getWindow();
        camere.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String status= Environment.getExternalStorageState();
                if(status.equals(Environment.MEDIA_MOUNTED)){//判断是否有SD卡
                  // 用户点击了从照相机获取
                    baseIntents.doTakePhoto();
                    dialog1.dismiss();
                }
                else{
                    Toast.makeText(context, "没有SD卡", Toast.LENGTH_SHORT).show();
                }
            }
        });
        pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             // 从相册中去获取
                baseIntents.doPickPhotoFromGallery();
                dialog1.dismiss();
            }
        });
        cancel1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog1.dismiss();
            }
        });
        dialog1.show();
        window.setGravity(Gravity.BOTTOM);

    }


    // 因为调用了Camera和Gally所以要判断他们各自的返回情况,他们启动时是这样的startActivityForResult
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case PHOTO_PICKED_WITH_DATA: {// 调用Gallery返回的
                //final Bitmap photo = data.getParcelableExtra("data");
                Bitmap photo = data.getParcelableExtra("data");
                String s = CropPictures.saveBitmapFile(photo, baseIntents.getPhotoFileName());
                imglist.add(s);
               switch (imglist.size()){
                   case 0:
                       break;
                   case 1:
                       hotimg2.setVisibility(View.VISIBLE);
                       break;
                   case 2:
                        hotimg3.setVisibility(View.VISIBLE);
                       break;
               }
                if (currentIndex==0){
                    hotimg1.setImageBitmap(photo);
                }else if (currentIndex==1){
                    hotimg2.setImageBitmap(photo);
                }else if (currentIndex==2){
                    hotimg3.setImageBitmap(photo);
                }
            }
            break;
            case CAMERA_WITH_DATA: {// 照相机程序返回的,再次调用图片剪辑程序去修剪图片
                baseIntents.doCropPhoto(baseIntents.mCurrentPhotoFile);
                break;
            }
            case PHOTO_TEXT:
                Uri data1 = data.getData();
                if (!TextUtils.isEmpty(data1.getAuthority())){
                    ContentResolver resolver = getContentResolver();
                    try {
                        photo = MediaStore.Images.Media.getBitmap(resolver, data1);

                        String[] proj = {MediaStore.Images.Media.DATA};
                        Cursor cursor = managedQuery(data1, proj, null, null, null);
                        if (cursor==null){
                            Toast.makeText(this, "没有找到图片", Toast.LENGTH_SHORT).show();
                        }else {
                            cursor.moveToFirst();
                            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                            //图片路径
                            path1 = cursor.getString(column_index);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    path1 = data1.getPath();
                }

                File file = new File(path1);
                baseIntents.doCropPhoto(file);
                break;
            case 2:
                backLink = (List) data.getSerializableExtra("back");
                if (backLink.size()==0){

                }else {
                    hotlink.setVisibility(View.VISIBLE);

                    distance = (List<Double>) data.getSerializableExtra("ddd");
                    for (int i = 1; i < backLink.size(); i++) {
                        cont = new HashMap<>();
                        String id = backLink.get(i).get("id");
                        Double dd = distance.get(i - 1)/1000;

                        cont.put("consigneeId",id);
                        cont.put("distance", df.format(dd));
                        contData.add(cont);
                    }

                    linktext.setText(backLink.get(0).get("name")+" "+backLink.get(0).get("address"));
                    listdata = new ArrayList<>();
                    for (int i = 1; i < backLink.size(); i++) {
                        listdata.add(backLink.get(i));
                    }
                    HotSendLinkItemAdapter adapter = new HotSendLinkItemAdapter(this, listdata);
                    gotlistview.setAdapter(adapter);
                    gotlistview.setEnabled(false);
                }

                break;
            case 100:
                Bundle extras = data.getExtras();
                String item = extras.getString("item");
                inExplain.setText(item);
                break;
        }

    }


}
